// Copyright 2007-2013 metaio GmbH. All rights reserved.
package com.asis.ra.demo;

import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.metaio.Template.R;
import com.metaio.sdk.ARViewActivity;
import com.metaio.sdk.MetaioDebug;
import com.metaio.sdk.jni.EPLAYBACK_STATUS;
import com.metaio.sdk.jni.IGeometry;
import com.metaio.sdk.jni.IMetaioSDKCallback;
import com.metaio.sdk.jni.MovieTextureStatus;
import com.metaio.sdk.jni.Rotation;
import com.metaio.sdk.jni.Vector2d;
import com.metaio.sdk.jni.Vector3d;
import com.metaio.tools.io.AssetsManager;

public class ImagenCamera extends ARViewActivity 


{
	private IGeometry mModel;
	private String path = "location/";
	
	private IGeometry videoButton;
	private IGeometry audioButton;
	private IGeometry textButton;
	
	private IGeometry movie;
	private IGeometry imagenes;
	
	public boolean isFirst = false;
	private Vector2d myPoint;
	
	private MetaioSDKCallbackHandler mCallbackHandler;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		videoButton = null;
		audioButton = null;
		textButton = null;
		
		movie = null;
		imagenes = null;
		mCallbackHandler = new MetaioSDKCallbackHandler();
		myPoint = new Vector2d();
	}
	
	
	@Override
	protected int getGUILayout() 
	{
		// Attaching layout to the activity
		return R.layout.tutorial1; 
	}


	public void onButtonClick(View v)
	{
		finish();
	}
	
	
	public void onMovieButtonClick(View v)
	{
		try
		{
			//imagenes.setVisible(false);
		
		}
		catch (NullPointerException e) {}
	}
	
	
	public void onModelButtonClick(View v)
	{
		try
		{
			//texto.setVisible(true);
			//imagenes.setVisible(false);
			//movie.setVisible(false);
			
			
		
		}
		catch (NullPointerException e) {}
	}
	
	
	@Override
	protected void onPause()
	{
		super.onPause();
		
		try
		{
			// Pause movie texture
			movie.pauseMovieTexture();
		}
		catch (NullPointerException e) {}
		
	}
	
	
	@Override
	protected void onResume()
	{
		super.onResume();
		
		try
		{		
			movie.startMovieTexture(true);
		}
		catch (NullPointerException e) {}
	}
	
	@Override
	protected void loadContents() 
	{
		try
		{
			
			String trackingConfigFile = AssetsManager.getAssetPath("TrackingData_MarkerlessFast.xml");
			boolean result = metaioSDK.setTrackingConfiguration(trackingConfigFile); 	
			MetaioDebug.log("Tracking data loaded: " + result); 
			
			videoButton = metaioSDK.createGeometryFromImage(AssetsManager.getAssetPath(path+"video.png"));
			audioButton = metaioSDK.createGeometryFromImage(AssetsManager.getAssetPath(path+"audio.png"));
			textButton = metaioSDK.createGeometryFromImage(AssetsManager.getAssetPath(path+"history.png"));
			
			final String moviePath = AssetsManager.getAssetPath("demo_movie.3g2");
			if (moviePath != null){
				movie = metaioSDK.createGeometryFromMovie(moviePath, true);
				if (movie != null){
			      movie.setScale(2.0f);
			      movie.setRotation(new Rotation(0f, 0f, (float)-Math.PI/2));
			      movie.setVisible(false);
			      movie.startMovieTexture(false);
			      MetaioDebug.log("Loaded geometry "+moviePath);
			      
			    } else {
			    	MetaioDebug.log(Log.ERROR, "Error loading geometry: "+moviePath);
			    }
			}
			
			
			DisplayMetrics displaymetrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
			int width = displaymetrics.widthPixels;
			
			float ancho = (width/2);
			
			videoButton.setTranslation(new Vector3d((ancho*-1)+280,70,0));
			videoButton.setVisible(true);
			
			audioButton.setTranslation(new Vector3d(ancho-280,70,0));
			audioButton.setVisible(true);
			
			textButton.setTranslation(new Vector3d(0,-70,0));
			textButton.setVisible(true);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public void playSound(){
		MediaPlayer mp = MediaPlayer.create(this, R.raw.clip);  
		mp.start();
	}

	private String createBillboardTexture(String billBoardTitle)
    {
           try
           {
                  final String texturepath = getCacheDir() + "/" + billBoardTitle + ".png";
                  
                  Bitmap billboard = null;
                  
                  String filepath = AssetsManager.getAssetPath(path);
                  Bitmap mBackgroundImage = BitmapFactory.decodeFile(filepath);
                  
                  billboard = mBackgroundImage.copy(Bitmap.Config.ARGB_8888, true); 
                  Canvas c = new Canvas(billboard);                  
                  Paint mPaint = new Paint();
                  mPaint.setColor(Color.WHITE);
                  mPaint.setTextSize(28);
                  mPaint.setTypeface(Typeface.DEFAULT_BOLD);
                  mPaint.setSubpixelText(true);
                  
                  float y = 50;
                  float x = 40;
                  
                  if (billBoardTitle.length() > 0)
                  {
                        String n = billBoardTitle.trim();
                        final int maxWidth = billboard.getWidth();
                        int i = mPaint.breakText(n, true, maxWidth, null);
                        c.drawText(n.substring(0, i), x, y, mPaint);
                        
                  }

                  try
                  {
                	  FileOutputStream out = new FileOutputStream(texturepath);
                      billboard.compress(Bitmap.CompressFormat.PNG, 90, out);
                      MetaioDebug.log("Texture file is saved to "+texturepath);
                      return texturepath;
                  } catch (Exception e) {
                      MetaioDebug.log("Failed to save texture file");
                	  e.printStackTrace();
                   }
                 
                  billboard.recycle();
                  billboard = null;

           } catch (Exception e)
           {
                  MetaioDebug.log("Error creating billboard texture: " + e.getMessage());
                  MetaioDebug.printStackTrace(Log.DEBUG, e);
                  return null;
           }
           return null;
    }
	
	
	@Override
	protected void onGeometryTouched(IGeometry geometry) 
	{
		
		playSound();
		geometry.setVisible(false);
		if (geometry.equals(videoButton))
		{
			textButton.setVisible(false);
			audioButton.setVisible(false);
			
			movie.setVisible(true);
			final MovieTextureStatus status = movie.getMovieTextureStatus();
			if (status.getPlaybackStatus() == EPLAYBACK_STATUS.EPLAYBACK_STATUS_STOPPED
					|| status.getPlaybackStatus() == EPLAYBACK_STATUS.EPLAYBACK_STATUS_PAUSED)
				movie.startMovieTexture(true);
		}if(geometry.equals(movie)){
			movie.stopMovieTexture();
			videoButton.setVisible(true);
			textButton.setVisible(true);
			audioButton.setVisible(true);
		}if(geometry.equals(audioButton)){
			MediaPlayer mp = MediaPlayer.create(this, R.raw.speech);  
			mp.start();
			videoButton.setVisible(true);
			textButton.setVisible(true);
			audioButton.setVisible(true);
		}
	}

	@Override
	protected IMetaioSDKCallback getMetaioSDKCallbackHandler()
	{
		return mCallbackHandler;
	}	


	final class MetaioSDKCallbackHandler extends IMetaioSDKCallback 
	{	
		@Override
		public void onSDKReady() 
		{
			runOnUiThread(new Runnable() 
			{
				@Override
				public void run() 
				{
					mGUIView.setVisibility(View.VISIBLE);
				}
			});
		}
	}
	

}
